﻿using Blog.Common.Helper;
using Blog.Framework.Exceptions;
using Blog.Framework.Internationalization;
using Blog.Models.Status;
using Blog.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using SqlSugar.Extensions;
using System.Net;

namespace Blog.WebApi.Filter
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
    public class GlobalExceptionsFilter : IAsyncExceptionFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _logger;

        public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> logger)
        {
            this._env = env;
            this._logger = logger;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {

            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.Code = ApiStatus.Error;
            ajaxResult.Msg = I18nMsg.tr(context.Exception.Message);

            //如果是开发环境
            if (_env.IsDevelopment())
            {
                ajaxResult.DevMsg = context.Exception.StackTrace;
            }

            context.Result = new JsonResult(ajaxResult);

            string msg = WriteLog(context.Exception.Message, context.Exception);
            _logger.LogError(msg);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("\r\n【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}", throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace);
        }
    }
}
